import React from 'react'
import PropTypes from 'prop-types'
import InputForm from '../controls/InputForm.jsx'
import CampaignService from '../../services/CampaignService.js'
import CancelOnUnmount from '../../services/CancelOnUnmount.js'
import GeoService from '../../services/GeoService.js'
import GeoCheckboxList from '../controls/GeoCheckboxList.jsx'
import Recommendations from '../controls/Recommendations.jsx'

export default class GeoTargeting extends React.Component {
  static propTypes = {
    campaignId: PropTypes.string.isRequired
  }

  constructor(props) {
    super(props)

    this.handleSaveButtonClicked = this.handleSaveButtonClicked.bind(this)
    this.handleRetry = this.handleRetry.bind(this)

    this.state = {
      isError: false,
      isSaving: false,
      isLoadingGeos: true,
      searchText: '',
      isLoadingSelectedGeos: true,
      selectedGeoIds: [],
      // allGeos: [],
      onRetry: this.initialCityLoad
    }
  }

  handleRetry() {
    this.setState({
      isError: false
    })

    this.state.onRetry()
  }

  componentWillUnmount() {
    CancelOnUnmount.handleUnmount(this)
  }

  handleSaveButtonClicked() {
    this.setState({
      isSaving: true
    })

    CancelOnUnmount.track(
      this,
      CampaignService.saveSelectedGeoIds(
        this.props.campaignId,
        this.state.selectedGeoIds
      )
        .catch(() => {
          this.setState({
            isError: true,
            onRetry: this.handleSaveButtonClicked
          })
        })
        .finally(() => {
          this.setState({
            isSaving: false
          })
        })
    )
  }

  render() {
    return (
      <div>
        <InputForm
          onSubmit={this.handleSaveButtonClicked}
          onRetry={this.handleRetry}
          isError={this.state.isError}
          isLoading={
            this.state.isLoadingGeos || this.state.isLoadingSelectedGeoIds
          }
          isSaving={this.state.isSaving}
        >
          <GeoCheckboxList />
        </InputForm>
        <Recommendations
          recommendationType="CAMPAIGN_GEO_RECOMMENDATIONS"
          campaignId={this.props.campaignId}
        />
      </div>
    )
  }
}
